package com.njwb.day14.dao.swing;

import com.njwb.day14.dao.pojo.Student;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.SQLException;
import java.util.List;

public class StudentView {
    private JFrame frame;
    private JTable table;
    private DefaultTableModel model;
    private StudentService service = new StudentService();

    public void show() {
        frame = new JFrame("学生信息管理");
        frame.setSize(1200, 800);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());

        // === 顶部查询面板 ===
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JTextField searchField = new JTextField(15);
        JButton searchButton = new JButton("查询");

        topPanel.add(new JLabel("姓名："));
        topPanel.add(searchField);
        topPanel.add(searchButton);
        frame.add(topPanel, BorderLayout.NORTH);

        // === 表格区域 ===
        String[] columns = {"编号", "姓名", "年龄", "地址", "操作"};
        model = new DefaultTableModel(columns, 0);
        table = new JTable(model);

        table.getColumn("操作").setCellRenderer(new ButtonRenderer());
        table.getColumn("操作").setCellEditor(new ButtonEditor(table, model, service));

        JScrollPane scrollPane = new JScrollPane(table);
        table.setRowHeight(35);
        table.setShowGrid(true);
        table.setGridColor(Color.GRAY);
        table.setIntercellSpacing(new Dimension(5, 5));

        table.getColumnModel().getColumn(0).setPreferredWidth(60);
        table.getColumnModel().getColumn(1).setPreferredWidth(120);
        table.getColumnModel().getColumn(2).setPreferredWidth(60);
        table.getColumnModel().getColumn(3).setPreferredWidth(200);
        table.getColumnModel().getColumn(4).setPreferredWidth(100);

        scrollPane.setPreferredSize(new Dimension(1100, 600));
        scrollPane.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));

        frame.add(scrollPane, BorderLayout.CENTER);

        // === 底部按钮面板 ===
        JButton addButton = new JButton("添加学生");
        JButton resetButton = new JButton("重置");
        JPanel bottomPanel = new JPanel();
        bottomPanel.add(addButton);
        bottomPanel.add(resetButton);
        frame.add(bottomPanel, BorderLayout.SOUTH);

        // === 添加按钮事件 ===
        addButton.addActionListener(e -> addStudent());

        // === 查询按钮事件 ===
        searchButton.addActionListener(e -> {
            String name = searchField.getText().trim();
            if (name.isEmpty()) {
                JOptionPane.showMessageDialog(frame, "请输入要查询的姓名！");
                return;
            }

            try {
                Student s = service.findStudentByName(name);
                model.setRowCount(0); // 清空原数据
                if (s != null) {
                    model.addRow(new Object[]{s.getSid(), s.getSname(), s.getAge(), s.getAddress(), "操作"});
                } else {
                    JOptionPane.showMessageDialog(frame, "未找到该学生！");
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(frame, "数据库错误！");
            }
        });

        // === 重置按钮事件 ===
        resetButton.addActionListener(e -> loadStudents());

        // 初始加载全部学生
        loadStudents();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private void loadStudents() {
        model.setRowCount(0);
        try {
            List<Student> students = service.getAllStudents();
            if (students == null || students.isEmpty()) {
                JOptionPane.showMessageDialog(frame, "暂无学生信息！");
                return;
            }
            for (Student s : students) {
                model.addRow(new Object[]{s.getSid(), s.getSname(), s.getAge(), s.getAddress(), "操作"});
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(frame, "加载学生信息失败！");
        }
    }


    private void addStudent() {
        String name = promptInput("请输入学生姓名：", "");
        if (name == null) return;

        String ageStr = promptInput("请输入学生年龄：", "");
        if (ageStr == null || !ageStr.matches("\\d+")) {
            JOptionPane.showMessageDialog(frame, "年龄输入无效！");
            return;
        }

        String address = promptInput("请输入学生地址：", "");
        if (address == null) return;

        Student stu = new Student(0, name, Integer.parseInt(ageStr), address);
        try {
            int result = service.addStudent(stu);
            if (result > 0) {
                loadStudents();
                JOptionPane.showMessageDialog(frame, "添加成功！");
            } else {
                JOptionPane.showMessageDialog(frame, "添加失败！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(frame, "数据库错误！");
        }
    }

    private String promptInput(String message, String defaultValue) {
        String input = JOptionPane.showInputDialog(frame, message, defaultValue);
        if (input == null || input.trim().isEmpty()) return null;
        return input.trim();
    }
}
